#!/usr/bin/env python
# coding=utf-8

from vavava.workqueue import Work
from vavava import util
from . import fetcher_auspost
from .. import taskworkbase

class AuspostWork(Work):
    def __init__( self, item_id, group, proxy=None, begin_time=None, period=None, log=None ):
        Work.__init__( self, period=period, group=group, begin_time=begin_time,
            log=log, name="[AuspostWork|%s]" % item_id )
        self.fetcher_ = fetcher_auspost.FetcherAuspost ( item_id=item_id, log=log )
        self.proxy_  = proxy

    def do(self,worker=None):
        self.fetcher_.SetDBConn(self._work_param)
        self.fetcher_.SetProxy(self.proxy_)
        self.fetcher_.Fetch()

    def __hash__(self):
        return hash(self.fetcher_.item_id)

class AuspostTaskWork(taskworkbase.TaskWorkBase):
    def __init__( self,period,group,begin_time=None, end_time=None,log=None,**kwarg ):
        taskworkbase.TaskWorkBase.__init__(
            self,track_type=1,period=period,group=group,begin_time=begin_time,
            end_time=end_time,log=log )
        if kwarg:
            proxy = kwarg.get("proxy")
            if proxy:
                self.proxy = kwarg["proxy"]

    def _get_all_items(self):
        return get_track_items_from_web(self.log)

    def _get_work_instance(self, item_id):
        return AuspostWork(
            item_id=item_id,
            group=self.group_id,
            proxy=self.proxy_,
            begin_time=None,
            period=None,
            log=self.log
        )

def get_track_items_from_web(log=None):
    """
    get list from "http://fastrackexpress.com.au/test.php?LIST=POST"
    and return  ItemList
    """
    from vavava.httpclient import HttpClient
    try:
        items = []
        client=HttpClient()
        html=client.Get(r"http://fastrackexpress.com.au/test.php?LIST=POST")
        htmlStr=html.decode('utf-8')
        reg_str=r'<td>(?P<id>[^<]*)</td>'
        idList = util.reg_helper(htmlStr,reg_str)
        item = idList[1:]
        return item
    except Exception as e:
        if log:
            log.excetpion(e)


